var express = require('express');
var mongoose=require('mongoose');
var fs=require('fs');
mongoose.Promise = global.Promise;
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//引入model
require('./models/db');
//引入路由文件
var index = require('./routes/index');
var users = require('./routes/users');
var category = require('./routes/category');
var articles = require('./routes/articles');
var chat = require('./routes/chat');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');

//引入数据库连接
mongoose.connect(require('./common/config').url);
mongoose.connection.on('error',function(err){
    console.log(err);
});
mongoose.connection.on('open',function(){
    console.log('数据库连接成功！');
});
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// app.set('view engine', 'html');
// app.engine('html',require('ejs').renderFile);
//配置session
app.use(session({
    secret: "blog",//secret 用来防止篡改 cookie
    key: "session_id",//key 的值为 cookie 的名字
    cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//设定 cookie 的生存期，这里我们设置 cookie 的生存期为 30 天
    resave:true,
    saveUninitialized:true,
    store: new MongoStore({mongooseConnection: mongoose.connection}),
    }));

app.use(flash());
app.use(function(req,res,next){
  res.locals.error=req.flash('error');
  res.locals.success=req.flash('success');
  res.locals.session_user='undefined'!= typeof req.session.user?req.session.user:'';
  next();
});
//自定义函数，用于ejs适用
app.locals.FormatDate=function (strTime) {
    var date = new Date(strTime);
    return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
};
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));

// 正常日志
var accessLog = fs.createWriteStream('./access.log', {flags: 'a'});
app.use(logger('dev',{stream: accessLog}));

// 错误日志
var errorLog = fs.createWriteStream('error.log', {flags: 'a'});
app.use(function (err, req, res, next) {
    var meta = '[' + new Date() + '] ' + req.url + '\n';
    errorLog.write(meta + err.stack + '\n');
    next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//上传资源
app.use(express.static(path.join(__dirname, 'uploads')));

app.use('/', index);
app.use('/users', users);
app.use('/articles', articles);
app.use('/category', category);
app.use('/chat', chat);
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   var err = new Error('Not Found');
//   err.status = 404;
//   next(err);
// });
app.use(function(req, res, next) {
  res.render('404',{title:'404页面'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
